import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid

from mcp.server.fastmcp import FastMCP

#实例mcp
mcp = FastMCP("Weather MCP Server")


#查询城市编号及其映射关系
@mcp.resource(
    uri="file:///query/city_code/{name}",
    name="city_code",
    description="根据城市或地区名称来查询城市编号及其映射关系，第一列为城市或地区名称，第二列地区编号adcode，第三列为城市编号citycode",
    mime_type="text/plain",
)
def query_city_code(name:str):
    """
    根据城市或地区名称来查询城市编号及其映射关系
    :param name: 城市或地区名称
    :return: 城市编号及其映射关系
    """
    #匹配的内容
    contents = ""
    with open("city_code.data", "r",encoding="utf-8") as f:
        #使用行遍历的方式，查找城市或地区名称（模糊匹配）
        for line in f.readlines():
            if name in line:
                print(" 【服务端-->query_city_code】匹配到的城市或地区名称:",line)
                contents += line
    return contents



@mcp.tool()
def get_city_weather(adcode: str):
    """
    根据地区编号查询天气信息
    :param adcode: 地区编号
    :return: 天气预报查询结果信息
    """
    key="d64c259dde4173ce7be767be32eb2bb9"
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={adcode}&key={key}"
    #调用高德天气API
    import requests
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return {"error": "Failed to fetch weather data"}

@mcp.tool()
def send_email(to:str, subject:str, content:str)->str:
    """
    发送电子邮件
    :param to: 收件人邮箱地址
    :param subject: 邮件主题
    :param content: 邮件内容
    :return: 发送反馈的结果信息
    """
    # 发件人邮箱配置
    sender = '15816469091@163.com'
    password = 'GEfMHKhcs2jLW3RK'
    smtp_server = 'smtp.163.com'
    smtp_port = 465

    try:
        # 创建邮件对象
        message = MIMEText(content, 'plain', 'utf-8')
        # 严格按照RFC5322格式设置From头
        message['From'] = f'<{sender}>'  # 发送人
        message['To'] = f'<{to}>'  # 收件人也用尖括号包裹
        message['Subject'] = Header(subject, 'utf-8')
        # 添加必要的邮件头
        message['Date'] = formatdate(localtime=True)
        message['Message-ID'] = make_msgid()

        # 连接SMTP服务器并发送邮件
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(sender, password)
            server.sendmail(sender, [to], message.as_string())

        print(f"邮件已成功发送到 {to}")
        return f"邮件已成功发送到 {to}"
    except Exception as e:
        error_msg = f"发送邮件时出错: {str(e)}"
        print(error_msg)
        return error_msg

if __name__ == "__main__":
     print(" MCP Server 启动中...")
     mcp.run(transport="sse")

